import { udp } from '@cscec/udp-ui';
import { schemaUtil } from '@/components/editor/util';
import { encodeParams } from '../common';

// 设计器默认portal内容
function getDefaultContent(title: string, useDefault = true) {
  return {
    title,
    id: udp.getQueryValue('id'),
    useFlg: 0,
    ...schemaUtil.getData({
      cache: false,
      schema: useDefault
        ? [
            {
              type: 'container',
              size: 'sm',
              body: [
                {
                  type: 'portal-banner',
                  name: 'portal-banner',
                  title: 'Hi，欢迎使用建造一体化平台!',
                  desc: '一站式应用管理入口，实现单点登录，实现业务信息聚合，打造千人千面的个性化工作台'
                }
              ]
            },
            {
              type: 'container',
              size: 'sm',
              body: [
                {
                  type: 'container',
                  body: [
                    {
                      type: 'portal-common-function',
                      name: 'portal-common-function',
                      title: '常用功能',
                      commonTitle: '最常使用',
                      recentlyTitle: '最近使用'
                    }
                  ]
                }
              ]
            },
            {
              type: 'container',
              size: 'sm',
              body: [
                {
                  type: 'container',
                  body: [
                    {
                      type: 'portal-approve-count',
                      name: 'portal-approve-count',
                      title: '审批汇总'
                    }
                  ]
                }
              ]
            },
            {
              type: 'container',
              size: 'sm',
              body: [
                {
                  type: 'grid',
                  columns: [
                    {
                      body: [
                        {
                          type: 'container',
                          body: [
                            {
                              type: 'portal-approve-pending',
                              name: 'portal-approve-pending',
                              title: '审批待办'
                            }
                          ]
                        }
                      ],
                      md: 8
                    },
                    {
                      body: [
                        {
                          type: 'container',
                          body: [
                            {
                              type: 'portal-common-task',
                              name: 'portal-common-task',
                              title: '文字列表'
                            }
                          ]
                        },
                        {
                          type: 'container',
                          style: { paddingTop: '1rem' },
                          body: [
                            {
                              type: 'portal-image-text',
                              name: 'portal-image-text',
                              title: '图文列表'
                            }
                          ]
                        }
                      ],
                      md: 4
                    }
                  ]
                }
              ]
            }
          ]
        : []
    }),
    typeId: udp.getQueryValue('category') || udp.getQueryValue('moduleCode') || undefined
  };
}

/**
 * 保存或更新工作台模板
 * @param params 工作台模板数据
 */
export async function saveOrUpdateWorkbenchTemplate(params: {
  id?: string;
  workbenchCode?: string;
  workbenchName: string;
  workbenchContent: string;
  useFlg: number;
  remark?: string;
  previewUrl?: string;
  templateType?: string;
  typeId?: string;
  tenantId?: string;
  recordVer?: string;
}) {
  const { code, message, data } = await udp.request.body({
    url: '/portal/workbenchTemplate/saveOrUpdateWorkbenchTemplate',
    data: encodeParams(params)
  });
  if (code === 0) {
    udp.message('保存成功！', 'success');
    return data;
  }
  udp.alert(message);
  return void 0;
}

/**
 * 通过id获取工作台界面模板信息详情
 * @param params 主键
 */
export async function getWorkbenchTemplateById(params: { id?: string }) {
  if (!params.id) {
    return getDefaultContent('工作台模板', false);
  }
  const { code, message, data } = await udp.request.get({
    url: '/portal/workbenchTemplate/getWorkbenchTemplateById',
    data: params
  });
  if (code === 0) {
    const wb = udp.parseJson(data?.workbenchContent);
    const packages = Object.keys(wb?.amisPackages || {}).length > 0 ? wb.amisPackages : undefined;
    return {
      title: data?.workbenchName,
      typeId: data.typeId,
      id: data?.id,
      value: wb,
      useFlg: data?.useFlg || 0,
      packages
    };
  }
  udp.alert(message);
  return null;
}

/**
 * 获取模板类型
 * @param params
 * @returns
 */
export async function getEnableWorkbenchType(params?: { typeName?: string }) {
  const { code, data } = await udp.request.get({
    url: '/portal/customWorkbenchType/getEnableWorkbenchType',
    data: params
  });
  return code === 0 ? data : [];
}

/**
 * 保存或更新工作台界面信息
 * @param params 工作台数据
 */
export async function saveOrUpdateCustomWorkbench(params: {
  id?: string;
  userId?: string;
  workbenchCode?: string;
  workbenchName: string;
  workbenchContent: string;
  useFlg: number;
  remark?: string;
  clearPersonal?: number;
}) {
  const { code, message, data } = await udp.request.body({
    url: '/portal/customWorkbench/saveOrUpdateCustomWorkbench',
    data: encodeParams(params)
  });
  if (code === 0) {
    udp.message(['保存成功！', '发布成功！'][params.useFlg], 'success');
    return data;
  }
  udp.alert(message);
  return void 0;
}

/**
 * 获取默认启用的工作台
 * @returns
 */
export async function getUserEnableWorkbench() {
  const { code, message, data } = await udp.request.get({
    url: '/portal/customWorkbench/getUserEnableWorkbench'
  });
  if (code === 0) {
    const wb = udp.parseJson(data?.workbenchContent);
    return { value: wb, packages: wb?.amisPackages };
  }
  udp.alert(message);
}

/**
 * 通过id获取工作台界面信息详情
 * @param params 主键
 */
export async function getUserWorkbenchById(params: { id?: string }) {
  if (!params.id) {
    return getDefaultContent('自定义工作台', false);
  }
  const { code, message, data } = await udp.request.get({
    url: '/portal/customWorkbench/getUserWorkbenchById',
    data: params
  });
  if (code === 0) {
    const wb = udp.parseJson(data?.workbenchContent);
    const packages = Object.keys(wb?.amisPackages || {}).length > 0 ? wb.amisPackages : undefined;
    return {
      title: data?.workbenchName,
      id: data?.id,
      value: wb,
      useFlg: data?.useFlg || 0,
      packages
    };
  }
  udp.alert(message);
  return null;
}

/**
 * 根据id获取模块首页
 * @param params
 * @returns
 */
export async function getHomepageNameById(params: { id?: string }) {
  if (!params.id) {
    return getDefaultContent('模块模板', false);
  }
  const { code, message, data } = await udp.request.get({
    url: '/integration-portal/moduleHomepage/getHomepageNameById',
    data: params
  });
  if (code === 0) {
    const wb = udp.parseJson(data?.homepageContent);
    const packages = Object.keys(wb?.amisPackages || {}).length > 0 ? wb.amisPackages : undefined;
    return {
      title: data?.homepageName,
      id: data?.id,
      value: wb,
      useFlg: data?.useFlg || 0,
      packages
    };
  }
  udp.alert(message);
  return null;
}

/**
 * 保存或更新工作台界面信息
 * @param params 工作台数据
 */
export async function saveOrUpdateModuleHomepage(params: {
  id?: string;
  appCode?: string;
  moduleCode?: string;
  homepageCode?: string;
  homepageName: string;
  homepageContent: string;
  useFlg: number;
  remark?: string;
  previewUrl?: string;
  recordVer?: number;
}) {
  const { code, message, data } = await udp.request.body({
    url: '/integration-portal/moduleHomepage/saveOrUpdate',
    data: encodeParams(params)
  });
  if (code === 0) {
    udp.message(['保存成功！', '发布成功！'][params.useFlg], 'success');
    return data;
  }
  udp.alert(message);
  return void 0;
}

/**
 * 传入一个模块编码获取已经启用的模块首页
 * @returns
 */
export async function getEnableHomepage(moduleCode) {
  const { code, message, data } = await udp.request.get({
    url: '/integration-portal/moduleHomepage/getEnableHomepage',
    data: {
      moduleCode
    }
  });
  if (code === 0) {
    const wb = udp.parseJson(data?.homepageContent);
    console.log('----wb-----: ', wb);
    return { value: wb, packages: wb?.amisPackages };
  }
  udp.alert(message);
}

/**
 * 传入一个模块编码获取已经启用的模块首页 - 个人
 * @param moduleCode
 * @returns
 */
export async function getPersonalEnableHomepage(moduleCode) {
  const { code, message, data } = await udp.request.get({
    url: '/integration-portal/personalModuleHomepage/getEnableHomepage',
    data: {
      moduleCode
    }
  });
  if (code === 0) {
    const wb = udp.parseJson(data?.personalHomepageContent);
    return {
      id: data?.id,
      value: wb || getDefaultContent('个人模块首页', false).value,
      packages: wb?.amisPackages,
      title: data?.personalHomepageName,
      homepageId: data?.homepageId,
      homepageVersion: data?.homepageVersion
    };
  }
  udp.alert(message);
}

/**
 * 根据id获取个人模块首页 - 个人
 * @param id
 * @returns
 */
export async function getPersonalHomepageById({ id }) {
  const { code, message, data } = await udp.request.get({
    url: '/integration-portal/personalModuleHomepage/getHomepageNameById',
    data: {
      id
    }
  });
  if (code === 0) {
    const wb = udp.parseJson(data?.personalHomepageContent);
    return {
      value: wb || getDefaultContent('个人模块首页', false).value,
      packages: wb?.amisPackages,
      title: data?.personalHomepageName,
      homepageId: data?.homepageId,
      homepageVersion: data?.homepageVersion
    };
  }
  udp.alert(message);
}

/**
 * 保存或更新工作台界面信息 - 个人首页
 * @param params
 * @returns
 */
export async function saveOrUpdatePersonalModuleHomepage(params: {
  id?: string;
  appCode?: string;
  homepageId?: number;
  homepageVersion?: string;
  moduleCode?: string;
  homepageCode?: string;
  homepageName: string;
  homepageContent: string;
  useFlg: number;
  remark?: string;
  previewUrl?: string;
  recordVer?: number;
}) {
  const { code, message, data } = await udp.request.body({
    url: '/integration-portal/personalModuleHomepage/saveOrUpdate',
    data: encodeParams({
      id: params.id,
      homepageId: params.homepageId,
      homepageVersion: params.homepageVersion,
      moduleCode: params.moduleCode,
      personalHomepageName: params.homepageName,
      personalHomepageContent: params.homepageContent
    })
  });
  if (code === 0) {
    udp.message(['保存成功！', '发布成功！'][params.useFlg], 'success');
    return data;
  }
  udp.alert(message);
  return void 0;
}
